<?php
namespace app\classs;

class Weixin
{
    // 预授权码
    public function pre_auth_code()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' . $this->component_access_token();
        $json = $this->curl($url,json_encode(['component_appid'=>get_default('s_appid')]));
        setLog('预授权码',$json);
        return json_decode($json)->pre_auth_code;
    }

    // 获取平台token
    function component_access_token()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
        $file = './web/system/api_component_token.php';

        if(!file_exists($file)){
            file_put_contents($file,'');
        }

        $token = json_decode(file_get_contents($file));
        
        setLog('获取平台token',$token);

        if($token && $token->expires_in > time()){
            return $token->component_access_token;
        }else{
            $default = get_default();
            $data['component_appid'] = $default['s_appid'];
            $data['component_appsecret'] = $default['s_secret'];
            $data['component_verify_ticket'] = file_get_contents('./web/system/verify_ticket.php');
            $json = $this->curl($url,json_encode($data));
            setLog('token',$json);
            $token = json_decode($json);
            $token->expires_in = $token->expires_in + time() - 300;
            
            file_put_contents($file,json_encode($token));

            return $token->component_access_token;
        }

    }

    // 授权链接
    public function pre_code($key = '',$type = 1)
    {
        $pre_auth_code = $this->pre_auth_code();
        $default = get_default();
        setLog('授权链接',$pre_auth_code);

        $redirect_uri = 'https://'.$_SERVER['SERVER_NAME'].$key;
        
        return 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$default['s_appid'].'&pre_auth_code='.$pre_auth_code.'&redirect_uri='.urlencode($redirect_uri).'&auth_type='.$type;
    }

    // 获取应用基本信息
    public function pre_code_info($auth_code_value = '')
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$this->component_access_token();
        $json = $this->curl($url,json_encode([
            'component_appid' => get_default('s_appid'),
            'authorization_code' => $auth_code_value
        ]));
        setLog('获取应用基本信息',$json);

        return json_decode($json);
    }

    // 获取公众号信息
    public function app_info($appid = '')
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$this->component_access_token();
        
        $json = $this->curl($url,json_encode([
            'component_appid' => get_default('s_appid'),
            'authorizer_appid' => $appid
        ]));
        setLog('获取公众号信息',$json);

        return json_decode($json);

    }

    // 设置小程序域名
    public function set_url()
    {
        $url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token='.$this->component_access_token();
        $pathUrl = 'https://'.$_SERVER['SERVER_NAME'];
        
        $data = [
            'action' => 'add',
            'requestdomain' => [$pathUrl],
            'wsrequestdomain' => [$pathUrl],
            'uploaddomain' => [$pathUrl],
            'downloaddomain' => [$pathUrl],
        ];

        $this->curl($url,$data);

        $url = 'https://api.weixin.qq.com/wxa/setwebviewdomain?access_token='.$this->component_access_token();

        $this->curl($url,[
            'action' => 'add' ,
            'webviewdomain' => [$pathUrl]
        ]);
    }

    // 用户登陆
    public function login($appid,$redirect_uri,$state)
    {
        // appid	是	公众号的appid
        // redirect_uri	是	重定向地址，需要urlencode，这里填写的应是服务开发方的回调地址
        // response_type	是	填code
        // scope	是	授权作用域，拥有多个作用域用逗号（,）分隔
        // state	否	重定向后会带上state参数，开发者可以填写任意参数值，最多128字节
        // component_appid	是	服务方的appid，在申请创建公众号服务成功后，可在公众号服务详情页找到
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope=snsapi_userinfo&state='.$state.'&component_appid='.get_default('s_appid');
    }

    // 获取用户openid
    public function loginDo($appid,$code = '')
    {
        // appid	是	公众号的appid
        // code	是	填写第一步获取的code参数
        // grant_type	是	填authorization_code
        // component_appid	是	服务开发方的appid
        // component_access_token	是	服务开发方的access_token
        $url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token?appid='.$appid.'&code='.$code.'&grant_type=authorization_code&component_appid='.get_default('s_appid').'&component_access_token=' . $this->component_access_token();
        return json_decode(file_get_contents($url),true);
    }

    // 获取用户信息
    public function loginDoInfo($token,$openid)
    {
        // appid	是	公众号的appid
        // code	是	填写第一步获取的code参数
        // grant_type	是	填authorization_code
        // component_appid	是	服务开发方的appid
        // component_access_token	是	服务开发方的access_token
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
        return json_decode(file_get_contents($url),true);
    }

    // 获取小程序用户信息
    public function xLoginInfo($appid,$code = '')
    {
        $url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid='.$appid.'&js_code='.$code.'&grant_type=authorization_code&component_appid='.get_default('s_appid').'&component_access_token='.$this->component_access_token();
        return json_decode(file_get_contents($url),true);
    }

    // 创建开放平台
    public function setCreate($appid)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/open/create?access_token='.$this->component_access_token();
        $json = $this->curl($url,json_encode([
            'appid' => $appid
        ]));
        setLog('创建开放平台',$json);

        return json_decode($json);
    }

    // 加入开放平台
    public function addCreate($appid,$open_appid)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/open/bind?access_token='.$this->component_access_token();
        $json = $this->curl($url,json_encode([
            'appid' => $appid,
            'open_appid' => $open_appid
        ]));	
        setLog('加入开放平台',$json);

        return json_decode($json);
    }

    // 获取开放平台
    public function getCreate($appid)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/open/get?access_token='.$this->component_access_token();
        $json = $this->curl($url,json_encode([
            'appid' => $appid,
        ]));	
        setLog('获取开放平台',$json);

        return json_decode($json);
    }

    // 获取权限
    public function getLimits()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token='.$this->component_access_token();
        $json = $this->curl($url,json_encode([
            'component_appid' => get_default('s_appid'),
            'offset' => 0,
            'count' => 500
        ]));	
        setLog('获取权限',$json);

        return json_decode($json);
    }



    
    function curl($url = '',$data = '')
    {
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

}
